class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret=new ArrayList<>();
        Arrays.sort(nums);
        int n=nums.length;
        for(int i=0;i<n;i++){
            for(int j=i+1;j<n;j++){
                int left=j+1;int right=n-1;
                long aim=(long)target-nums[i]-nums[j];
                while(left<right){
                    int sum=nums[left]+nums[right];
                    if(sum<aim){
                        left++;
                    }else if(sum>aim){
                        right--;
                    }else{
                        ret.add(Arrays.asList(nums[i],nums[j],nums[left++],nums[right--]));
                        while(left<right&&nums[left]==nums[left-1]) left++;
                        while(left<right&&nums[right]==nums[right+1]) right--;
                    }
                }
                while(j<n-1&&nums[j]==nums[j+1]) j++;
            }
            while(i<n-1&&nums[i]==nums[i+1]) i++;
        }
        return ret;
    }
}